<template>
	<view>
		<view class="search-box">
			<uni-search-bar  @input="input" :radius="100" :bgColor="'#ffffff'" cancel-button="none" :focus="true"></uni-search-bar>
		</view>
		<!-- 搜索列表展示 -->
		<view class="sugg-list" v-if="kw.length!==0">
			<view class="sugg-item" v-for="(item,index) in searchResults" :key="index" @click="gotoDetail(item)">
				<view class="goods-name">{{item.goods_name}}
				</view>
				<uni-icons type="arrowright" size="16"></uni-icons>
			</view>
		</view>
		<!-- 搜索历史 -->
		<view class="history-box" v-else>
			<!-- 标题区域 -->
			<view class="history-title">
				<text>搜索历史</text>
				<uni-icons type="trash" size="20" @click="clean"></uni-icons>
			</view>
			<!-- 列表区域 -->
			<view class="history-list">
				<uni-tag :text="item" v-for="(item,index) in histories" :key="index" @click="gotoGoodsList(item)"></uni-tag>
			</view>
		</view>
	</view>

</template>

<script>
	export default {
		data() {
			return {
				timer:null,
				//记录输入的内容
				kw:'',
				//存放搜索的结果
				searchResults:[],
				// 存放搜索历史
				historyList:[],
				historyList2:['a','app','apple'],
				reversehistoryList:[]
			};
		},
		//加载搜索记录
		onLoad() {
			this.historyList=JSON.parse(uni.getStorageSync('kw')|| '[]')
		},
		methods:{
			delay(ms){
				return new Promise(resolve=>setTimeout(resolve,ms))
			},
			// input函数接收输入框的内容
			input(e){
				// 规定500毫秒没有输入再打印输入框内容
				clearTimeout(this.timer)
				this.timer=setTimeout(()=>{
					// console.log(e)
					this.kw=e
					this.getSearchList()
					
				},500)
			},
			async getSearchList(){
				//判断搜索关键词是否为空
				if(this.kw===0){
					this.searchResults=[]
					return
				}
				const query=this.kw;
				const{data:res} = await uni.$http.get(`/api/public/v1/goods/qsearch?query=${encodeURIComponent(query)}`)
				// console.log(res)
				await this.delay(500)
				// console.log(res)
				if(res.meta.status!==200){
					//防止清理搜索框（当有输入变为无输入时），让函数以为没有传参数而返回400
					if(res.meta.status!==400){
						return uni.$showMsg(undefined,undefined,"none")
					}
				}
				this.searchResults=res.message
				
				//当获得搜索列表后，将搜索关键字添加到historyList
				this.saveSearchHistory()
				//直接使用unshift就可以不用函数
				// this.historyList2.unshift(this.kw)
				
			},
			gotoDetail(item){
				// console.log(item.goods_id)
				uni.navigateTo({
					url:'/subpkg/goods_detail/goods_detail?goods_id='+item.goods_id
				})
			},
			saveSearchHistory(){
				//push这是将元素添加到数组尾部
				if(this.kw==='') return
				// this.historyList.push(this.kw)
				const set=new Set(this.historyList)
				set.delete(this.kw)
				set.add(this.kw)
				// console.log(set)
				this.historyList=Array.from(set)
				//对搜索历史数据，进行持久化存储
				uni.setStorageSync('kw',JSON.stringify(this.historyList))
				//unshift这是将元素添加到数组尾部
				// this.historyList.unshift(this.kw)
				//但是视频选择用reverse()函数
				// this.delay(500)
				// this.reversehistoryList=[]
				//弹幕笔记：使用include()或indexof()可以查找数组内是否有该元素，然后通过条件判断，使用splice()进行删除，然后用unshift()进行队头添加
				},
				clean(){
					const that=this;
					// this.historyList=[]
					// uni.setStorageSync('kw','[]')
					uni.showModal({
						title:'提示',
						content:'是否清除搜索记录',
						success:function(res){
							if(res.confirm){
								that.historyList=[]
								uni.setStorageSync('kw','[]')
							}
							else{
								console.log("用户点击取消")
							}
						}
					})
				},
				gotoGoodsList(kw){
					uni.navigateTo({
						url:'/subpkg/goods_list/goods_list?query='+kw
					})
				}
				
			},
			computed:{
			histories(){
				return [...this.historyList].reverse()
				//弹幕中最简单的方法,记得解开注释this.historyList.push(this.kw)或者return [...new Set([this.kw,...this.historyList].reverse())]进行创建添加
				// return [...new Set([...this.historyList].reverse())]
				//以下是自己实验的代码
				// for(let i=0;i<this.historyList.length;i++){
				// 	this.reversehistoryList.push(this.historyList[i])
				// }
				// return this.reversehistoryList.reverse()
			}
		}
	}
</script>

<style lang="scss">
	
.uni-searchbar{
	background-color: #c00000;
}
.search-box{
	position: sticky;
	top:0;
	z-index: 999;
}
.sugg-list{
	padding: 0 5px;
	.sugg-item{
		display: flex;
		align-items: center;
		justify-content: space-between;
		font-size: 12;
		padding: 13px 0px;
		border-bottom: 1px solid #efefef;
		.goods-name{
			// 文字不允许换行
			white-space: nowrap;
			// 溢出部分隐藏
			overflow: hidden;
			// 文本溢出后,用...代替
			text-overflow: ellipsis;
		}
	}
}
.history-box{
	padding:0 5px;
		.history-title{
			display: flex;
			justify-content: space-between;
			height: 40px;
			align-items: center;
			font-size:13px;
			border-bottom: 1px solid #efefef;
		}
		.history-list{
			display: flex;
			flex-wrap: wrap;
			.uni-tag--default.data-v-1516016e{
				color: black;
				background-color: #D3D3D3;
			}
			.uni-tag{
				margin-top: 5px;
				margin-right: 5px;
			}
		}
	}
</style>
